package com.example.demo.modules.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.example.demo.common.util.ParameterUtils;
import com.example.demo.common.vo.ResultVo;
import com.example.demo.modules.service.UserService;
import com.example.demo.modules.vo.UserVo;

@Controller
@RequestMapping("user")
public class UserController {
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);
	@Autowired
	private UserService userService;
	@Autowired
	private SecurityManager securityManager;

	@RequestMapping("page/login")
	public String redirectLogin() {
		return "user/user-login";
	}

	@RequestMapping("login")
	@ResponseBody
	public ResultVo userLogin(UserVo userVo) {
		Subject subject = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(userVo.getUserName(), userVo.getUserPass());
		ResultVo resultVo = new ResultVo();
		try {
			securityManager.login(subject, token);
		} catch (AuthenticationException e) {
			logger.error("用户登录错误", e);
			resultVo.setCode(1);
		}
		// 成功
		return resultVo;
	}

	@RequestMapping("logout")
	public String logout() {
		Subject subject = SecurityUtils.getSubject();
		securityManager.logout(subject);
		return "user/user-login";
	}

	@RequestMapping("page/register")
	public String redirectRegister() {
		return "user/user-register";
	}

	@RequestMapping(value = "register", method = RequestMethod.POST)
	@ResponseBody
	public ResultVo register(UserVo userVo) {
		logger.debug("参数: " + userVo);
		ParameterUtils.handle(userVo);
		ResultVo resultVo = new ResultVo();
		try {
			userService.createUser(userVo);
		}catch (Exception e) {
			logger.error("用户注册失败", e);
			resultVo.setCode(1);
		}
		return resultVo;
	}

	/**
	 * 检查用户名是否存在
	 * 
	 * @param userName
	 * @return
	 */
	@RequestMapping("check/{username}")
	@ResponseBody
	public ResultVo checkUserNameExists(@PathVariable("username") String userName) {
		ResultVo resultVo = new ResultVo();
		// 存在
		if (userService.checkUserNameExists(userName)) {
			resultVo.setCode(1);
		}
		return resultVo;
	}
}
